package cn.tnar.parkservice.service.impl;


import cn.tnar.parkservice.mapper.InvoiceDataMapper;
import cn.tnar.parkservice.mapper.InvoiceMapper;
import cn.tnar.parkservice.mapper.TApplyTicketAcctInfoMapper;
import cn.tnar.parkservice.model.dto.InvoiceDetailDTO;
import cn.tnar.parkservice.model.entity.Invoice;
import cn.tnar.parkservice.model.entity.TApplyTicketAcctInfo;
import cn.tnar.parkservice.model.request.InvoiceRedRequest;
import cn.tnar.parkservice.model.response.InvoiceDetailResponse;
import cn.tnar.parkservice.model.response.QueryInvoiceDetailResponse;
import cn.tnar.parkservice.service.BWInvoiceService;
import cn.tnar.parkservice.util.ParkingUtil;
import cn.tnar.pms.kesb.KesbClient;
import cn.tnar.pms.kesb.KesbException;
import cn.tnar.pms.kesb.KesbParam;
import com.baiwang.bop.client.BopException;
import com.baiwang.bop.client.ILoginClient;
import com.baiwang.bop.client.impl.BopRestClient;
import com.baiwang.bop.client.impl.PostLogin;
import com.baiwang.bop.request.impl.LoginRequest;
import com.baiwang.bop.request.impl.invoice.common.InvoiceDetails;
import com.baiwang.bop.request.impl.invoice.common.InvoiceMainInfo;
import com.baiwang.bop.request.impl.invoice.impl.FormatfileBuildRequest;
import com.baiwang.bop.request.impl.invoice.impl.InvoiceOpenRequest;
import com.baiwang.bop.request.impl.invoice.impl.InvoiceQueryRequest;
import com.baiwang.bop.respose.entity.FormatfileBuildResponse;
import com.baiwang.bop.respose.entity.InvoiceOpenResponse;
import com.baiwang.bop.respose.entity.InvoiceQueryResponse;
import com.baiwang.bop.respose.entity.LoginResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @author: yl
 * @date 2018/10/16 14:30
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class BWInvoiceServiceImpl extends ServiceImpl<InvoiceMapper, Invoice> implements BWInvoiceService {
    private static final Logger log = LoggerFactory.getLogger(BWInvoiceServiceImpl.class);

    private static String bwToken;
    private static String bwTokenExpTime;
    private static BopRestClient bwClient;

/*
    @Value("${tnar.invoice.bwUrl}")
    private String bwUrl;
    @Value("${tnar.invoice.bwKey}")
    private String bwKey;
    @Value("${tnar.invoice.bwSecret}")
    private String bwSecret;
    @Value("${tnar.invoice.bwUsername}")
    private String bwUsername;
    @Value("${tnar.invoice.bwPassword}")
    private String bwPassword;
    @Value("${tnar.invoice.bwSalt}")
    private String bwSalt;
    @Value("${tnar.invoice.bwTaxNo}")
    private String bwTaxNo;*/
/*    @Value("${tnar.invoice.bwGoodsCode}")
    private String bwGoodsCode;*/
 /*   @Value("${tnar.invoice.parkMsgUrl}")
    private String parkMsgUrl;*/


    @Autowired
    InvoiceDataMapper invoiceDataMapper;

    @Autowired
    TApplyTicketAcctInfoMapper applyTicketAcctInfoMapper;

    @Autowired
    private KesbClient kc;

    private ArrayList<String> bwParkList = new ArrayList<>();
    private ArrayList<BopRestClient> bwClientList = new ArrayList<>();
    private ArrayList<String> bwTokenList = new ArrayList<>();
    private ArrayList<String> bwTokenExpTimeList = new ArrayList<>();


    @Override
    public QueryInvoiceDetailResponse getQueryInvoiceV2(Long start_time, Long end_time, Integer state, int invoice_type, int buyer_type, String park_code, int size, int page) {
        QueryInvoiceDetailResponse resp = new QueryInvoiceDetailResponse();
        //state:1开票中；3开票成功；4开票失败；5已冲红
        if (state == null || state+"" == ""){
            state = 0;
        }
        if (invoice_type == 1){
            //blue
            invoice_type = 0;
        }else if(invoice_type == 2){
            //red
            invoice_type = 1;
        }else{
            invoice_type = 2;
        }

        if (5 == state){
            state = 0;
            invoice_type =1;
        }else if(4 == state || 3 == state || 1 == state){
            invoice_type = 0;
        }

        --page;
        if (page < 0){
            page = 0;
        }
        log.info("getQueryInvoiceV2:"+state+";"+invoice_type+";"+buyer_type+";"+size+";"+page);
        QueryInvoiceDetailResponse.ApplyInvoiceResponse res = new QueryInvoiceDetailResponse.ApplyInvoiceResponse();
        //张数
        List<Map<String, Object>> list = invoiceDataMapper.getInvoiceList(start_time, end_time, state, invoice_type, buyer_type, park_code, size, page);
        List<Map<String, Object>> lst = new ArrayList<>();
        if (list.size() > 0){
            for (int i = 0; i < list.size(); i ++){
                Map<String,Object> map = list.get(i);
                map.put("ticket_total_amount_has_tax", map.get("order_amount"));
                map.put("state", map.get("invoice_status"));
                map.put("create_at", map.get("invoice_time"));
                map.put("buy_name", map.get("buyer_title"));
                map.put("buy_acct", map.get("we_chat_name"));
                map.put("buy_tel", map.get("tel_no"));
                map.put("buyer_type", map.get("buyer_type"));
                map.put("g_unique_id", map.get("invoice_provider_sno"));
                map.put("order_no", map.get("invoice_apply_sno"));
                if (1 == Integer.parseInt(map.get("is_red").toString())){
                    map.put("has_red", "1");
                    map.put("is_red", "0");
                }else{
                    map.put("has_red", "0");
                    map.put("is_red", "0");
                }
                lst.add(map);
                log.info("index="+i+";id="+list.get(i).get("id").toString()+";is_red="+map.get("is_red")+";has_red="+map.get("has_red"));
            }
        }
        res.setList(lst);
        int count = invoiceDataMapper.getInvoiceCount(start_time,end_time,state,invoice_type,buyer_type);
        res.setSize(size);
        log.info("total="+count+";list size="+list.size());
        res.setTotal(count);
        res.setTotal_page(count/size+1);
        res.setPage(page+"");
        resp.setData(res);
        resp.setCode(9000);
        return resp;
    }


    @Override
    public List<Map<String,Object>> getRelation(String app_sno,String orderNo) {
        List<Map<String,Object>> resp = invoiceDataMapper.getRelationV2(app_sno, orderNo);
        if (resp != null && resp.size() > 0){
            for (int i = 0; i < resp.size(); i ++){
                if (Integer.parseInt(String.valueOf(resp.get(i).get("parktime"))) <= 0){
                    List<Map<String,Object>> parking = invoiceDataMapper.getParkingInfo(null, String.valueOf(resp.get(i).get("order_no")));
                    if (parking != null && parking.size() > 0){
                        if (Integer.parseInt(String.valueOf(parking.get(0).get("time1"))) > 0){
                            Map<String,Object> info = resp.get(i);
                            info.put("parktime", String.valueOf(parking.get(0).get("time1")));
                            resp.set(i, info);
                        }else if (Integer.parseInt(String.valueOf(parking.get(0).get("time2"))) > 0){
                            Map<String,Object> info = resp.get(i);
                            info.put("parktime", String.valueOf(parking.get(0).get("time2")));
                            resp.set(i, info);
                        }
                    }
                }
            }
        }
        return resp;
    }

    /**
     * 根据停车场，流水号查询发票详情
     * @param param parkCode serialNo
     * @return
     */
    @Override
    public InvoiceDetailDTO selectInvoiceDetailBySerialNo(Map<String,String> param){
        String serialNo = param.get("serialNo");
        List<Map<String,Object>>  info = invoiceDataMapper.getInvoiceAllInfo(serialNo);
        String parkCode = String.valueOf(info.get(0).get("park_code"));
        return this.selectInvoiceDetail(serialNo,parkCode);
    }

    /**
     * 根据流水号查询单个发票详情
     * @param serialNo
     * @return
     */
    @Override
    public InvoiceDetailDTO selectInvoiceDetail(String serialNo,String parkCode) {

        String taxNo = applyTicketAcctInfoMapper.getParkTaxNo(parkCode);
        try {
            InvoiceQueryRequest queryRequest = new InvoiceQueryRequest();
            queryRequest.setSellerTaxNo(taxNo);
            //查询类型 1发票流水号查询  2发票号码和发票代码查询 3纳税人识别号【销方】
            // 4开票终端标识 5开票日期起止  6.购方信息 7.机构代码 9.保单号 10.快递单号 11业务流水号
            queryRequest.setInvoiceQueryType("1");
            queryRequest.setSerialNo(serialNo);
            InvoiceQueryResponse response = this.getBwClient(parkCode).execute(queryRequest, this.getBwToken(parkCode), InvoiceQueryResponse.class);
            InvoiceMainInfo invoiceMainInfo = null;
            if(response.getInvoiceList().size()>0){
                invoiceMainInfo = response.getInvoiceList().get(0);
            }
            InvoiceDetailDTO invoiceDetailDTO = new InvoiceDetailDTO();
            invoiceDetailDTO.setApplyDate(invoiceMainInfo.getInvoiceDate());

            //由于地址和电话联合,正则将其分离
            String buyerAddressPhone = invoiceMainInfo.getBuyerAddressPhone();
            String reg = "[^\u4e00-\u9fa5]";
            String address = buyerAddressPhone.replaceAll(reg, "");
            String tel = buyerAddressPhone.replace(address,"");
            invoiceDetailDTO.setBuyerAddress(address);
            invoiceDetailDTO.setBuyerTel(tel);

            String[] buyInfo = buyerAddressPhone.split("-");
            if (buyInfo.length >= 2){
                invoiceDetailDTO.setBuyerAddress(buyInfo[0]);
                String buyerTel = buyerAddressPhone.replace(buyInfo[0]+"-","");
                invoiceDetailDTO.setBuyerTel(buyerTel);
            }

            //同样的方法分离银行和账号
            String bankAccount = invoiceMainInfo.getBuyerBankAccount();
            String bank = bankAccount.replace(reg,"");
            String account = bankAccount.replace(bank,"");
            invoiceDetailDTO.setBuyerBank(bank);
            invoiceDetailDTO.setBuyerAccount(account);


            invoiceDetailDTO.setInvoiceCode(invoiceMainInfo.getInvoiceCode());
            invoiceDetailDTO.setInvoiceType(invoiceMainInfo.getInvoiceType());
            invoiceDetailDTO.setInvoiceName(invoiceMainInfo.getBuyerName());

            //invoiceDetailDTO.setInvoicePrice(invoiceMainInfo.getInvoiceTotalPrice());
            invoiceDetailDTO.setInvoicePrice(invoiceMainInfo.getInvoiceTotalPriceTax());
            invoiceDetailDTO.setBuyerTaxNo(invoiceMainInfo.getBuyerTaxNo());
            invoiceDetailDTO.setBuyerName(invoiceMainInfo.getBuyerName());
            invoiceDetailDTO.setBuyerPhone(invoiceMainInfo.getBuyerPhone());

            List<Map<String,Object>>  info = invoiceDataMapper.getInvoiceAllInfo(serialNo);
            if (info != null && info.size() > 0){
                invoiceDetailDTO.setBuyerBank(String.valueOf(info.get(0).get("buyer_bank_name")));
                invoiceDetailDTO.setBuyerAccount(String.valueOf(info.get(0).get("buyer_bank_account")));
                invoiceDetailDTO.setBuyerPhone(String.valueOf(info.get(0).get("tel_no")));

                invoiceDetailDTO.setBuyerName(String.valueOf(info.get(0).get("we_chat_name")));
            }
            return invoiceDetailDTO;
        }
        catch(BopException e){
            log.error("百旺发票调用错误===>"+e.getErrMsg());
            return null;
        }
    }


/*
    @Override
    public InvoiceDetailDTO selectInvoiceDetail(String serialNo) {

        try {
            InvoiceQueryRequest queryRequest = new InvoiceQueryRequest();
            queryRequest.setSellerTaxNo(bwTaxNo);
            //查询类型 1发票流水号查询  2发票号码和发票代码查询 3纳税人识别号【销方】
            // 4开票终端标识 5开票日期起止  6.购方信息 7.机构代码 9.保单号 10.快递单号 11业务流水号
            queryRequest.setInvoiceQueryType("1");
            queryRequest.setSerialNo(serialNo);
            InvoiceQueryResponse response = this.getBwClient().execute(queryRequest, this.getBwToken(), InvoiceQueryResponse.class);
            InvoiceMainInfo invoiceMainInfo = null;
            if(response.getInvoiceList().size()>0){
                invoiceMainInfo = response.getInvoiceList().get(0);
            }
            InvoiceDetailDTO invoiceDetailDTO = new InvoiceDetailDTO();
            invoiceDetailDTO.setApplyDate(invoiceMainInfo.getInvoiceDate());

            //由于地址和电话联合,正则将其分离
            String buyerAddressPhone = invoiceMainInfo.getBuyerAddressPhone();
            String reg = "[^\u4e00-\u9fa5]";
            String address = buyerAddressPhone.replaceAll(reg, "");
            String tel = buyerAddressPhone.replace(address,"");
            invoiceDetailDTO.setBuyerAddress(address);
            invoiceDetailDTO.setBuyerTel(tel);

            String[] buyInfo = buyerAddressPhone.split("-");
            if (buyInfo.length >= 2){
                invoiceDetailDTO.setBuyerAddress(buyInfo[0]);
                invoiceDetailDTO.setBuyerTel(buyInfo[1]);
            }

            //同样的方法分离银行和账号
            String bankAccount = invoiceMainInfo.getBuyerBankAccount();
            String bank = bankAccount.replace(reg,"");
            String account = bankAccount.replace(bank,"");
            invoiceDetailDTO.setBuyerBank(bank);
            invoiceDetailDTO.setBuyerAccount(account);


            invoiceDetailDTO.setInvoiceCode(invoiceMainInfo.getInvoiceCode());
            invoiceDetailDTO.setInvoiceType(invoiceMainInfo.getInvoiceType());
            invoiceDetailDTO.setInvoiceName(invoiceMainInfo.getBuyerName());

            //invoiceDetailDTO.setInvoicePrice(invoiceMainInfo.getInvoiceTotalPrice());
            invoiceDetailDTO.setInvoicePrice(invoiceMainInfo.getInvoiceTotalPriceTax());
            invoiceDetailDTO.setBuyerTaxNo(invoiceMainInfo.getBuyerTaxNo());
            invoiceDetailDTO.setBuyerName(invoiceMainInfo.getBuyerName());
            invoiceDetailDTO.setBuyerPhone(invoiceMainInfo.getBuyerPhone());

            List<Map<String,Object>>  info = invoiceDataMapper.getInvoiceAllInfo(serialNo);
            if (info != null && info.size() > 0){
                invoiceDetailDTO.setBuyerBank(String.valueOf(info.get(0).get("buyer_bank_name")));
                invoiceDetailDTO.setBuyerAccount(String.valueOf(info.get(0).get("buyer_bank_account")));
                invoiceDetailDTO.setBuyerPhone(String.valueOf(info.get(0).get("tel_no")));

                invoiceDetailDTO.setBuyerName(String.valueOf(info.get(0).get("we_chat_name")));
            }
            return invoiceDetailDTO;
        }
        catch(BopException e){
            e.printStackTrace();
            return null;
        }
    }
*/


    //百望token
    public String getBwToken(String parkCode) {
        TApplyTicketAcctInfo invoiceConfig = getConfigByParkCode(parkCode);
        if(ParkingUtil.isNullEmpty(bwToken)
                || ParkingUtil.isNullEmpty(bwTokenExpTime)
                || (Long.parseLong(ParkingUtil.getTime()) >= Long.parseLong(bwTokenExpTime))){
            ILoginClient loginClient = new PostLogin(invoiceConfig.getUrl());
            LoginRequest loginRequest = new LoginRequest();
            loginRequest.setAppkey(invoiceConfig.getAppId());
            loginRequest.setAppSecret(invoiceConfig.getAppSecret());
            loginRequest.setUserName(invoiceConfig.getUserName());
            loginRequest.setPasswordMd5(invoiceConfig.getPassWord());
            loginRequest.setUserSalt(invoiceConfig.getAppSalt());
            LoginResponse loginResponse = loginClient.login(loginRequest);

            bwToken=loginResponse.getAccess_token();//记录
            log.info("bwToken refresh:token="+bwToken+";exp_time="+loginResponse.getExpires_in());
            bwTokenExpTime = ParkingUtil.currentPlusMinutes(loginResponse.getExpires_in()/60-60);
        }
        return bwToken;
    }


    public BopRestClient getBwClient(String parkCode){
        TApplyTicketAcctInfo invoiceConfig = getConfigByParkCode(parkCode);
        if (bwClient == null){
            bwClient = new BopRestClient(invoiceConfig.getUrl(), invoiceConfig.getAppId(), invoiceConfig.getAppSecret());
            log.info("bwClient init:url="+invoiceConfig.getUrl()+";key="+invoiceConfig.getAppId()+";sec="+invoiceConfig.getAppSecret());
        }
        return bwClient;
    }



    @Override
    public InvoiceDetailResponse redInvoiceBW(InvoiceRedRequest lst){
        InvoiceDetailResponse resp = new InvoiceDetailResponse();
        if (ParkingUtil.isNotNullEmpty(lst.getB_trade_no()) || ParkingUtil.isNotNullEmpty(lst.getSerialNo())){
            try {
                String sno = lst.getB_trade_no();
                if (ParkingUtil.isNullEmpty(sno)){
                    sno = lst.getSerialNo();
                }
                //流水号查询发票详情
                List<Map<String,Object>>  info = invoiceDataMapper.getInvoiceAllInfo(sno);
                if (info != null && info.size() > 0){
                    String park_code = String.valueOf(info.get(0).get("park_code"));
                    String price = String.valueOf(info.get(0).get("order_amount"));
                    //查询停车场抬头
                    KesbParam mapPark = new KesbParam();
                    mapPark.put("park_code", park_code);
                    List<Map<String, String>> list = null;
                    try {
                        list = kc.requestList("70102011", mapPark);
                    } catch (KesbException e) {
                        log.error("查询开票抬头失败 kesb error:", e.getMessage());
                    } catch (IOException e) {
                        log.error("查询开票抬头失败 io error:", e.getMessage());
                    }
                    if (list == null || list.size() == 0){
                        resp.setCode(200);
                        resp.setMsg("开票停车场未配置");
                        return resp;
                    }
                    //发票详情
                    InvoiceQueryRequest detailReq = new InvoiceQueryRequest();
                    detailReq.setInvoiceQueryType("1");
                    detailReq.setSellerTaxNo(list.get(0).get("taxpayerId"));
                    detailReq.setSerialNo(sno);

                    InvoiceQueryResponse detailResp = this.getBwClient(park_code).execute(detailReq,this.getBwToken(park_code),InvoiceQueryResponse.class);
                    log.info("detail code="+detailResp.getCode()+";msg="+detailResp.getMessage());
                    if (ParkingUtil.isNullEmpty(detailResp.getCode()) && detailResp.getInvoiceList().size() == 1) {
                        String orderNo = String.valueOf(info.get(0).get("invoice_apply_sno"))+"_"+ParkingUtil.nowBasicTime();

                        //开红票
                        InvoiceOpenRequest request = new InvoiceOpenRequest();
                        request.setDeviceType("0");
                        request.setSerialNo(orderNo);
                        request.setReqSerialNumber("");
                        request.setBusinessId("");
                        request.setTaxationMode("0");
                        request.setInvoiceType("1");
                        request.setInvoiceTypeCode("026");
                        request.setInvoiceSpecialMark("00");
                        request.setSellerTaxNo(list.get(0).get("taxpayerId"));
                        request.setInvoiceTerminalCode(list.get(0).get("enterpriseCode"));
                        if("2".equals(String.valueOf(info.get(0).get("buyer_type")))){
                            request.setBuyerTaxNo(String.valueOf(info.get(0).get("buyer_taxcode")));
                        }else{
                            request.setBuyerTaxNo("");
                        }
                        request.setBuyerName(String.valueOf(info.get(0).get("buyer_title")));
                        request.setBuyerAddressPhone(String.valueOf(info.get(0).get("buyer_address"))+"-"+String.valueOf(info.get(0).get("buyer_phone")));
                        request.setBuyerBankAccount(String.valueOf(info.get(0).get("buyer_bank_account")));
                        request.setDrawer(list.get(0).get("kpy"));
                        request.setPayee(list.get(0).get("sky"));
                        request.setChecker(list.get(0).get("fhy"));
                        request.setInvoiceListMark("0");
                        request.setRedInfoNo("");
                        request.setNotificationNo("");
                        request.setOriginalInvoiceCode(detailResp.getInvoiceList().get(0).getInvoiceCode());//TODO
                        request.setOriginalInvoiceNo(detailResp.getInvoiceList().get(0).getInvoiceNo());//TODO
                        request.setDeductibleAmount("");
                        request.setSignatureParameter("0000004282000000");
                        request.setTaxDiskNo("");
                        request.setGoodsCodeVersion("");
                        request.setConsolidatedTaxRate("");
                        request.setInvoiceSample("06");
                        request.setAutoSplit(false);
                        request.setRemarks("");

                        log.info("tax info:total_price="+price);
                        request.setInvoiceTotalPrice("");
                        request.setInvoiceTotalTax("");
                        request.setInvoiceTotalPriceTax("");

                        List<InvoiceDetails> invoiceDetailsList = new ArrayList<InvoiceDetails>();
                        InvoiceDetails invoiceDetails = new InvoiceDetails();
                        invoiceDetails.setGoodsLineNo("0");
                        invoiceDetails.setGoodsLineNature("0");
//                        invoiceDetails.setGoodsCode(bwGoodsCode);
                        invoiceDetails.setGoodsExtendCode("");
                        invoiceDetails.setGoodsName("红票-金额:"+price);
                        invoiceDetails.setGoodsTaxItem("");
                        invoiceDetails.setGoodsSpecification("");
                        invoiceDetails.setGoodsUnit("");
                        invoiceDetails.setGoodsQuantity("-1");
                        invoiceDetails.setGoodsPrice(String.format("%.02f", ParkingUtil.toFen(price)/100.0));
                        invoiceDetails.setGoodsTotalPrice("-"+String.format("%.02f", ParkingUtil.toFen(price)/100.0));
                        invoiceDetails.setGoodsTotalTax("");
                        invoiceDetails.setGoodsTaxRate(list.get(0).get("sl"));
                        invoiceDetails.setGoodsDiscountLineNo("");
                        invoiceDetails.setPriceTaxMark("1");
                        invoiceDetails.setVatSpecialManagement("");
                        invoiceDetails.setFreeTaxMark("");
                        invoiceDetails.setPreferentialMark("0");
                        invoiceDetailsList.add(invoiceDetails);
                        request.setInvoiceDetailsList(invoiceDetailsList);

                        InvoiceOpenResponse gpRsp = this.getBwClient(park_code).execute(request, this.getBwToken(park_code), InvoiceOpenResponse.class);
                        if (ParkingUtil.isNullEmpty(gpRsp.getCode())) {
                            String wxOrderId = orderNo;

                            //生产板式
                            FormatfileBuildRequest request2 = new FormatfileBuildRequest();
                            request2.setSellerTaxNo(list.get(0).get("taxpayerId"));
                            request2.setInvoiceCode(gpRsp.getInvoiceCode());
                            request2.setInvoiceNo(gpRsp.getInvoiceNo());
                            if (ParkingUtil.isNotNullEmpty(list.get(0).get("buyer_email")) || ParkingUtil.isNotNullEmpty(list.get(0).get("buyer_phone"))) {
                                request2.setPushType("1");
                                request2.setBuyerEmail(list.get(0).get("buyer_email"));

                                request2.setBuyerPhone(list.get(0).get("buyer_phone"));
                            } else {
                                request2.setPushType("0");
                                request2.setBuyerEmail("");
                                request2.setBuyerPhone("");
                            }

                            FormatfileBuildResponse resp2 = this.getBwClient(park_code).execute(request2, this.getBwToken(park_code), FormatfileBuildResponse.class);
                            if (ParkingUtil.isNullEmpty(resp2.getCode())) {
                                String urlRed = resp2.getData();

                                //更新信息
                                HashMap map =new HashMap<>();
                                map.put("pdf_red", urlRed);
                                map.put("order_id", sno);//商户订单
                                //更新发票状态
                                updateRedStateV2(map);

                                //
            /*                    try{
                                    String order_no = info.get(0).get("invoice_apply_sno").toString();
                                    String wx_openid = info.get(0).get("wx_openid").toString();
                                    String ticket_money = String.valueOf(info.get(0).get("order_amount"));
                                    String ticket_date =info.get(0).get("apply_time").toString();
                                    String buy_name =info.get(0).get("buyer_title").toString();

                                    Map<String, String> bizMap = new HashMap<>(10);
                                    bizMap.put("openId", wx_openid);
                                    bizMap.put("order_no", order_no);
                                    bizMap.put("buy_name", buy_name);
                                    bizMap.put("ticket_money", ticket_money);
                                    bizMap.put("ticket_date", ticket_date);
                                    LinkedMultiValueMap<String, String> queryMap = new LinkedMultiValueMap<>();
                                    queryMap.setAll(bizMap);
                                    //推送用户冲红信息
                                    String url = UriComponentsBuilder.fromHttpUrl(parkMsgUrl).queryParams(queryMap).toUriString();
                                    Request requestRed = new Request.Builder().url(url).build();
                                    // 发送请求
                                    log.info("red_push_user:"+url);
                                    OkHttpClient httpClient = new OkHttpClient.Builder()
                                            .addInterceptor((chain) -> {
                                                Request req = chain.request().newBuilder().addHeader("Connection", "close").build();
                                                return chain.proceed(req);
                                            }).build();
                                    httpClient.newCall(requestRed).execute();
                                }catch (Exception e){
                                    e.printStackTrace();
                                    log.error("err info:"+e.getMessage());
                                }*/

                                resp.setCode(0);
                                resp.setMsg("");
                            }else{
                                resp.setCode(102);
                                resp.setMsg(resp2.getMessage());
                            }
                        }else{
                            resp.setCode(101);
                            resp.setMsg(gpRsp.getMessage());
                        }
                    }else{
                        resp.setCode(101);
                        resp.setMsg("查询发票有误");
                    }
                }else{
                    resp.setCode(100);
                    resp.setMsg("冲红订单有误");
                }
            } catch (BopException e){
                log.error("发票冲红异常===>"+e.getErrMsg());
                resp.setCode(101);
                if (ParkingUtil.isNotNullEmpty(e.getSubMessage())){
                    resp.setMsg(e.getSubMessage());
                }else if (ParkingUtil.isNotNullEmpty(e.getErrMsg())){
                    resp.setMsg(e.getErrMsg());
                }else{
                    resp.setMsg("发票冲红失败！");
                }
            }catch (Exception e) {
                log.error("冲红失败！", e);
                resp.setCode(100);
                resp.setMsg(e.getMessage());
            }
        }else{
            log.error("冲红订单有误:"+lst);
            resp.setCode(10);
            resp.setMsg("冲红订单有误");
        }

        return resp;
    }

    @Override
    public void updateRedStateV2(HashMap map) {
        invoiceDataMapper.updateRedStateV2(String.valueOf(map.get("pdf_red")), String.valueOf(map.get("order_id")));
    }

    /**
     * 根据停车场查询发票配置信息
     */
    private TApplyTicketAcctInfo getConfigByParkCode(String parkCode){
        QueryWrapper<TApplyTicketAcctInfo> qw = new QueryWrapper<>();
        qw.eq("park_code", parkCode);
        qw.last("limit 1");
        return applyTicketAcctInfoMapper.selectOne(qw);
    }
}
